<template>
  <div :class="$options.name">
    <el-upload
      v-show="!resultImg"
      ref="fileUpload"
      :action="action"
      :data="uploadData"
      :on-change="selectChange"
      :show-file-list="false"
      :auto-upload="false"
      :http-request="httpRequest"
      :with-credentials= "false"
      class="upload-el"
      accept="image/*"
      name="pic">
      <div>
        <span
          class="icon upload-icon" />
        <el-button size="small" type="primary">选择图片</el-button>
      </div>
      <!-- <div
        slot="tip"
        class="el-upload__tip">
        图片大小不超过5M，推荐图片尺寸宽高比9:16
      </div> -->
    </el-upload>
    <figure
      v-show="resultImg"
      class="result-img">
      <img
        :src="resultImg">
      <el-button
        @click="updateCropper">重新上传</el-button>
    </figure>
    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      :fixed-number="fixedNumber"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg" />
  </div>
</template>

<script>
import config from '@/utils/config';
import Cropper from '@/components/cropper/uploadImage'
// import { baseAxios } from '@common/axios';
// import { loading } from '@common';
import axios from 'axios'
import { Message } from 'element-ui';
export default {
  name: 'UploadImg',
  components: {
    Cropper
  },
  props: {
    imgType: {
      type: String,
      default: ''
    },
    fixedNumber: {
      type: Array,
      default: () => {
        return [16, 9]
      }
    }
  },
  data() {
    return {
      uploadData: { // 上传需要的额外参数
        siteId: 1,
        source: 1
      },
      action: config.BaseUrl + '/storage/create',
      cropperImg: '', // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      uploadFile: '', // 裁剪后的文件
      resultImg: '' // 上传成功，后台返回的路径
    };
  },
  methods: {

    base64ToFile(urlData, fileName) {
      const arr = urlData.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bytes = atob(arr[1]); // 解码base64
      let n = bytes.length
      const ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
    // submit 之后会触发此方法
    httpRequest(request) {
      const { action, data, filename, file } = request;
      //   console.log('action:', action)
      //   console.log('data:', data)
      //   console.log('filename:', filename)
      console.log('request', request)
      // 新建formDate对象
      const formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      // console.log(this.uploadFile)
      // 文件单独push,第三个参数指定上传的文件名
      // formData.append(filename, this.uploadFile, data.fileName);

      //   console.log('this.uploadFile:', this.uploadFile)
      //   console.log('filename:', filename)
      console.log('this.uploadFile]', this.uploadFile)
      //   console.log('file:', file)
      // const blobToFiles = new window.File([this.uploadFile], file.name, { type: file.type })
      const blobToFiles = new File([this.uploadFile], file.name, { type: file.type, lastModified: Date.now() });
      console.log(blobToFiles)
      formData.append('file', blobToFiles);
      // loading.start(); // 上传中的loading
      axios({
        headers: {
          contentType: 'multipart/form-data' // 需要指定上传的方式
        },
        url: config.BaseUrl + '/storage/create',
        method: 'post',
        data: formData,
        timeout: 200000000 // 防止文件过大超时
      }).then(res => {
        console.log(res)

        if (res.data.code === '200') {
          Message.success('图片上传成功')
          this.$emit('modalShowFn', res.data.data.url)
        //   if (this.imgType === 'slt') {
        //       this.$emit('modalShowFn', res.data.data.url)
        //   }

        //   if (this.imgType === 'lbt') {

        //   }
        } else {
          Message.error(res.message || '网络错误');
        }
        // loading.close();
        // const { code, data, msg } = resp || {};
        // console.log('code:', code)
        // console.log('data:', data)
        // console.log('msg:', msg)
        // if (code === 0) {
        //   this.$message.success('图片上传成功');
        //   this.resultImg = data; // 上传成功后展示的图片
        // } else {
        //   this.$message.error(msg || '网络错误');
        // }
        this.showCropper = false
      }).catch(err => {
        // loading.close();
        console.log(err);
      });
    },
    // 选择文件
    selectChange(file) {
      const { raw } = file;
      this.openCropper(raw);
    },
    /**
     * @param {file} 上传的文件
      */
    openCropper(file) {
      var files = file;
      const isLt5M = files.size > (5 << 20);
      if (isLt5M) {
        this.$message.error('请上传5M内的图片');
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files);
      this.showCropper = true;
    },
    // 上传图片
    uploadImg(file) {
      this.uploadFile = file;
      this.$refs.fileUpload.submit();
    },
    // 更新图片
    updateCropper() {
      this.$refs.fileUpload.$children[0].$el.click();
    },
    // 关闭窗口
    closeDialog() {
      this.showCropper = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.UploadImg {
  .video-image {
    display: flex;
    figure {
      width: 100px;
      img {
        width: 100%;
        display: block;
      }
    }
  }
}
</style>
